<template>
	<view v-if="show" class="overlay">
		<view class="countdown-box">
			<text class="countdown-number">{{ count }}</text>
			<text class="countdown-text">
				{{ type === '54321' ? '请准备开始高位下拉' : '请确保设备竖直静止3s，测试过程上升阶段尽可能快速' }}
			</text>
		</view>
	</view>
</template>

<script>
	import VueEvent from '../../VueEvent';

	export default {
		props: {
			type: {
				type: String,
				default: '321', // '321' 或 '54321'
				validator: v => ['321', '54321'].includes(v)
			}
		},
		data() {
			return {
				show: false,
				count: 3,
				audioFiles: [],
				audioInstances: [],
			};
		},
		computed: {
			countdownTexts() {
				if (this.type === '54321') {
					return ['五', '四', '三', '二', '一', '开始'];
				}
				return ['三', '二', '一', '开始'];
			}
		},
		methods: {
			clearAudioInstances() {
				this.audioInstances.forEach(ins => { try { ins.destroy(); } catch(e) {} });
				this.audioInstances = [];
			},
			async preloadAudios() {
				const pluginSI = requirePlugin("WechatSI");
				const promises = this.countdownTexts.map((text, index) => {
					return new Promise((resolve) => {
						pluginSI.textToSpeech({
							lang: "zh_CN",
							tts: true,
							content: text,
							success: (res) => {
								wx.downloadFile({
									url: res.filename,
									success: (downloadRes) => {
										this.audioFiles[index] = downloadRes.tempFilePath;
										resolve();
									},
									fail: resolve
								});
							},
							fail: resolve
						});
					});
				});
				await Promise.all(promises);
			},
			async startCountdown() {
				this.clearAudioInstances();
				this.show = true;
				this.count = this.type === '54321' ? 5 : 3;
				if (this.audioFiles.length === 0) {
					await this.preloadAudios();
				}
				const startTime = Date.now();
				let expectedTime = startTime;
				for (let i = 0; i < this.countdownTexts.length; i++) {
					this.count = this.type === '54321' ? 5 - i : 3 - i;
					if (this.audioFiles[i]) {
					this.playAudioImmediately(i);
					}
					expectedTime += 1000;
					const now = Date.now();
					const delay = Math.max(0, expectedTime - now);
					await new Promise(resolve => setTimeout(resolve, delay));
				}
				this.show = false;
				this.$emit('end');
			},
			playAudioImmediately(index) {
				if (VueEvent.sharedData.isMuted || !this.audioFiles[index]) return;
				const audio = wx.createInnerAudioContext();
				this.audioInstances.push(audio);
				audio.src = this.audioFiles[index];
				audio.playbackRate = 1.3;
				audio.autoplay = true;
				audio.onEnded = audio.onError = () => {
					try { audio.destroy(); } catch(e) {}
					this.audioInstances = this.audioInstances.filter(ins => ins !== audio);
				};
			}
		},
		beforeDestroy() {
			this.clearAudioInstances();
		}
	};
</script>

<style scoped>
	/* 遮罩层 */
	.overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	/* 倒计时容器 */
	.countdown-box {
		text-align: center;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	/* 倒计时大数字 */
	.countdown-number {
		font-size: 220rpx;
		font-weight: bold;
		color: rgba(110, 88, 170, 1);
		animation: fadeInOut 0.5s ease-in-out forwards;
		margin-bottom: 50rpx;
	}

	/* 提示文字 */
	.countdown-text {
		width: 500rpx;
		font-size: 40rpx;
		font-weight: 600;
		color: rgba(255, 255, 255, 1);
		text-shadow: 2rpx 2rpx 10rpx rgba(0, 0, 0, 0.6);
		text-align: center;
		margin-top: 20rpx;
	}

	/* 动画时间缩短为0.5秒 */
	@keyframes fadeInOut {
		0% {
			opacity: 0;
			transform: scale(1.2);
		}
		50% {
			opacity: 1;
			transform: scale(1);
		}
		100% {
			opacity: 1;
			transform: scale(1);
		}
	}
</style>